<?php
namespace application\admin\controller;
use application\common\controller\Base;
use application\common\model\User;
use think\Session;

class Teacher extends Base
{
    public function addTeacher() {
		if (! ($this->request->has('teacherName','post') && $this->request->has('teacherPassword','post'))) {
			$this->assign([
				'active' => [1,11],
				'title' => '新增教师',
				'messageCount' => 0,
			]);
			return $this->fetch();
		}else {
            $teacherName = $this->request->post('teacherName');
            $teacherPassword = md5($this->request->post('teacherPassword'));
            $user = new User();
            $user->user_name = $teacherName;
            $user->user_password = $teacherPassword;
            $user->user_role = 2;
            $result = $user->save();
            if ($result) {
                $this->redirect('index/index');
            }else {
                throw new HttpException(500);
            }
        }
	}
	public function manageTeacher() {
        $user = new User();
        $result = $user->where(['user_role' => 2,])->paginate(Session::get('pageNum'));
        $this->assign([
            'active' => [1,12],
            'title' => '教师管理',
            'messageCount' => 0,
            'teachers' => $result,
        ]);
        return $this->fetch();
    }
	public function deleteTeacher() {
        $user = new User();
        $teachers = input('post.items/a');
        $data = [];
        foreach($teachers as $teacher) {
            $data = [
                'user_name' => $teacher,
                'user_role' => 2,
            ];
            User::destroy($data);
        }
        $result = $user->where(['user_role' => 2,])->select();
        $this->assign([
            'active' => [1,12],
            'title' => '删除教师',
            'messageCount' => 0,
            'teachers' => $result,
        ]);
        $this->redirect('manageTeacher');
	}
	public function addManager() {
        $user = new User();
        $teacher = $this->request->get('teacher');
        $user->save([
            'user_role' => 1,
        ],[
            'user_name' => $teacher,
            'user_role' => 2,
        ]);
        $this->redirect('manageTeacher');
    }
	public function notifyTeacher() {
		$this->assign([
			'active' => [1,13],
			'title' => '通知教师',
			'messageCount' => 0,
		]);
		return $this->fetch();
	}
	public function checkNameRepeat() {
	    $user = new User();
	    if (!$this->request->isAjax()) {
            $this->error("服务器错误！","admin/index/index");
        }else {
	        $teacherName = $this->request->post('name');
	        $result = $user->where(['user_name' => $teacherName,'user_role' => 2])->find();
	        if ($result) {
	            return '{"result":"true"}';
            }else {
	            return '{"result":"false"}';
            }
        }
    }
}